
import { onMounted } from 'vue'

type Options = {
    el: string
}


// 自定义hooks 做一个图片转base64

export default function(options: Options): Promise<{baseUrl: string}> {
    return new Promise((resolve) => {
        onMounted(() => {
            let img: HTMLImageElement = document.querySelector(options.el) as HTMLImageElement
            console.log(img);
            img.onload = () => {        // 图片加载完的再去转
                resolve({
                    baseUrl: base64(img)
                })
            }
        })

        const base64 = (el: HTMLImageElement) => {
            // 使用canvas 转图片
            const canvas = document.createElement('canvas')
            const ctx = canvas.getContext('2d')             // 创建画布
            canvas.width = el.width
            canvas.height = el.height
            ctx?.drawImage(el,0,0,canvas.width, canvas.height)                        // 画图片
            return canvas.toDataURL('image/png')                                    // toDataURL 导出base64
        }
    })
} 